package com.kxmall.admin.controller.vehicle.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kxmall.common.core.domain.PageQuery;
import com.kxmall.common.core.page.TableDataInfo;
import com.kxmall.common.enums.VehicleStatusType;
import com.kxmall.common.exception.ServiceException;
import com.kxmall.common.helper.LoginHelper;
import org.apache.commons.lang3.StringUtils;
import com.kxmall.vehicle.domain.KxVehicleBoxUpGoods;
import com.kxmall.vehicle.domain.KxVehicleInGoods;
import com.kxmall.vehicle.domain.KxVehicle;
import com.kxmall.vehicle.domain.bo.KxVehicleBoxInGoodsBo;
import com.kxmall.vehicle.domain.vo.KxVehicleBoxUpGoodsVo;
import com.kxmall.vehicle.domain.vo.KxVehicleInGoodsVo;
import com.kxmall.vehicle.domain.vo.KxVehicleVo;
import com.kxmall.vehicle.mapper.KxVehicleBoxUpGoodsMapper;
import com.kxmall.vehicle.mapper.KxVehicleInGoodsMapper;
import com.kxmall.vehicle.mapper.KxVehicleMapper;
import com.kxmall.admin.controller.vehicle.service.IKxVehicleBoxUpGoodsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品入柜Service业务层处理
 */
@RequiredArgsConstructor
@Service
public class KxVehicleBoxUpGoodsServiceImpl implements IKxVehicleBoxUpGoodsService {

    @Autowired
    private KxVehicleMapper vehicleMapper;
    @Autowired
    private KxVehicleInGoodsMapper vehicleInGoodsMapper;
    @Autowired
    private KxVehicleBoxUpGoodsMapper vehicleBoxUpGoodsMapper;

    /**
     * 查询商品入柜
     */
    @Override
    public KxVehicleBoxUpGoodsVo queryById(Long id) {
        KxVehicleBoxUpGoodsVo kxVehicleBoxUpGoodsVo = vehicleBoxUpGoodsMapper.selectVoById(id);
        List<KxVehicleInGoodsVo> inVehicleProductVoList = vehicleInGoodsMapper.selectVoList(
                new LambdaQueryWrapper<KxVehicleInGoods>().eq(KxVehicleInGoods::getInVehicleOrder, kxVehicleBoxUpGoodsVo.getGoodsNumbers()));
        //kxVehicleBoxUpGoodsVo.setVehicleInProductVoList(inVehicleProductVoList);
        return kxVehicleBoxUpGoodsVo;
    }

    /**
     * 查询商品入柜列表
     */
    @Override
    public TableDataInfo<KxVehicleBoxUpGoodsVo> queryPageList(KxVehicleBoxInGoodsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<KxVehicleBoxUpGoods> lqw = buildQueryWrapper(bo);
        Page<KxVehicleBoxUpGoodsVo> result = vehicleBoxUpGoodsMapper.selectVoPage(pageQuery.build(), lqw);
        List<KxVehicle> vehicle = vehicleMapper.selectList();
//        result.getRecords().stream()
//            .filter(record -> vehicle.stream().anyMatch(storage -> storage.getId().equals(record.getVehicleId())))
//            .forEach(record -> record.setVehicleName(vehicle.stream()
//                .filter(storage -> storage.getId().equals(record.getVehicleId()))
//                .findFirst()
//                .map(KxVehicle::getName)
//                .orElse(null)));
        return TableDataInfo.build(result);
    }

    /**
     * 查询商品入柜列表
     */
    @Override
    public List<KxVehicleBoxUpGoodsVo> queryList(KxVehicleBoxInGoodsBo bo) {
        LambdaQueryWrapper<KxVehicleBoxUpGoods> lqw = buildQueryWrapper(bo);
        return vehicleBoxUpGoodsMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<KxVehicleBoxUpGoods> buildQueryWrapper(KxVehicleBoxInGoodsBo bo) {
        LambdaQueryWrapper<KxVehicleBoxUpGoods> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getVehicleId() != null, KxVehicleBoxUpGoods::getVehicleId, bo.getVehicleId());
        //lqw.eq(StringUtils.isNotBlank(bo.getInVehicleNumbers()), KxVehicleBoxUpGoods::getInVehicleNumbers, bo.getInVehicleNumbers());
        //lqw.eq(bo.getStates() != null, KxVehicleBoxUpGoods::getStates, bo.getStates());
        lqw.eq(StringUtils.isNotBlank(bo.getInPerson()), KxVehicleBoxUpGoods::getUpPerson, bo.getInPerson());
        lqw.eq(bo.getInTime() != null, KxVehicleBoxUpGoods::getUpTime, bo.getInTime());
        //lqw.eq(StringUtils.isNotBlank(bo.getIngoingDay()), KxVehicleBoxUpGoods::getIngoingDay, bo.getIngoingDay());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), KxVehicleBoxUpGoods::getRemarks, bo.getRemarks());
        return lqw;
    }

    /**
     * 新增商品入柜
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(KxVehicleBoxInGoodsBo bo) {
        //自动生成入柜单号,O+年月日+流水号
        //查询数据库最新生成的编号
        KxVehicleBoxUpGoods selectByMax = vehicleBoxUpGoodsMapper.selectByMax();
        String max_code = "";//定义数据库的截取的数据
        String in_skock = "";//定义拼接好的字符串
//        if (selectByMax != null) {
//            max_code = selectByMax.getInVehicleNumbers();
//        }
        //定义时间字符串拼接
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String uid_pfix = simpleDateFormat.format(new Date());
        //判断数据库是否有数据
        if (max_code != null && max_code.contains(uid_pfix)) {
            String uid_end = max_code.substring(9, 14);
            Integer endNum = Integer.parseInt(uid_end);
            //100001
            endNum = 100000 + endNum + 1;
            String num = endNum + "";
            //去掉100001中的首位1
            String numm = num.substring(1);
            in_skock = "I" + uid_pfix + numm;
        } else {
            //数据库没数据时
            in_skock = "I" + uid_pfix + "00001";
        }
        //入柜商品加入数据库
//        List<KxVehicleInGoodsVo> productVoList = bo.getInVehicleProductVoList();
//        if (!CollectionUtils.isEmpty(productVoList)) {
//            for (KxVehicleInGoodsVo VehicleProductVo : productVoList) {
//                VehicleProductVo.setInVehicleNumbers(in_skock);
//                KxVehicleInGoods vehicleProduct = BeanUtil.toBean(VehicleProductVo, KxVehicleInGoods.class);
//                if (inVehicleProductMapper.insert(vehicleProduct) <= 0) {
//                    throw new ServiceException("入柜商品添加失败");
//                }
//            }
//        }
        //入柜添加
        KxVehicleBoxUpGoods goodsUpVehicleBox = BeanUtil.toBean(bo, KxVehicleBoxUpGoods.class);
        //goodsUpVehicleBox.setInVehicleNumbers(in_skock);
        //goodsUpVehicleBox.setStates(GoodsUpVehicleBoxType.TO_BE_FOR_VEHICLE.getCode());
        goodsUpVehicleBox.setUpdateTime(new Date());
        if (vehicleBoxUpGoodsMapper.insert(goodsUpVehicleBox) <= 0) {
            throw new ServiceException("管理员系统未知异常");
        }
        return true;
    }

    /**
     * 修改商品入柜
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(KxVehicleBoxInGoodsBo bo) {
        LambdaQueryWrapper<KxVehicleInGoods> wrapper = new LambdaQueryWrapper<>();
        //wrapper.like(KxVehicleInGoods::getInVehicleNumbers, bo.getInVehicleNumbers());
        if (vehicleInGoodsMapper.delete(wrapper) <= 0) {
            throw new ServiceException("入柜商品更新失败");
        }
        //入柜商品加入数据库
//        List<KxVehicleInGoodsVo> VehicleProductVoList = bo.getInVehicleProductVoList();
//        if (!CollectionUtils.isEmpty(VehicleProductVoList)) {
//            for (KxVehicleInGoodsVo inVehicleProductVo : VehicleProductVoList) {
//                KxVehicleInGoods vehicleProduct = BeanUtil.toBean(inVehicleProductVo, KxVehicleInGoods.class);
//                if (inVehicleProductMapper.insert(vehicleProduct) <= 0) {
//                    throw new ServiceException("入柜商品添加失败");
//                }
//            }
//        }
        KxVehicleBoxUpGoods goodsUpVehicleBox = BeanUtil.toBean(bo, KxVehicleBoxUpGoods.class);
        goodsUpVehicleBox.setUpdateTime(new Date());
        if (vehicleBoxUpGoodsMapper.updateById(goodsUpVehicleBox) > 0) {
            return true;
        }
        throw new ServiceException("管理员系统未知异常");

    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(KxVehicleBoxUpGoods entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商品入库
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<KxVehicleBoxUpGoodsVo> goodsInVehicleVos = vehicleBoxUpGoodsMapper.selectVoBatchIds(ids);
        //删除入库信息
        if (vehicleBoxUpGoodsMapper.deleteBatchIds(ids) <= 0) {
            throw new ServiceException("入库商品删除失败");
        }
        for (KxVehicleBoxUpGoodsVo inVehicleVo : goodsInVehicleVos) {
            //批量删除入库商品
            LambdaQueryWrapper<KxVehicleInGoods> wrapper = new LambdaQueryWrapper<>();
            //wrapper.like(KxVehicleInGoods::getInVehicleNumbers, inVehicleVo.getInVehicleNumbers());
            if (vehicleInGoodsMapper.delete(wrapper) <= 0) {
                throw new ServiceException("入库商品删除失败");
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUpVehicleBox(KxVehicleBoxInGoodsBo bo) {
//        if (ObjectUtils.isEmpty(bo.getVehicleId()) && StringUtils.isEmpty(bo.getInVehicleNumbers())) {
//            throw new ServiceException("参数不能为空");
//        }
        //根据入柜的商品数量更新餐车的数量
        LambdaQueryWrapper<KxVehicleInGoods> wrapper = new LambdaQueryWrapper<>();
        //wrapper.eq(KxVehicleInGoods::getInVehicleNumbers, bo.getInVehicleNumbers());
        List<KxVehicleInGoods> inVehicleProducts = vehicleInGoodsMapper.selectList(wrapper);
        Long inVehicleCount;//入柜数量
        for (KxVehicleInGoods inVehicleProduct : inVehicleProducts) {
            inVehicleCount = inVehicleProduct.getInVehicleCount();
            Long productAttrId = inVehicleProduct.getProductAttrId();
//            if (vehicleGoodsMapper.updateVehicleGoodsForAdd(bo.getVehicleId(), productAttrId, inVehicleCount) <= 0) {
//                throw new ServiceException("更新商品库存失败");
//            }
        }
        //更新入柜状态
        KxVehicleBoxUpGoods kxVehicleBoxUpGoods = new KxVehicleBoxUpGoods();
        //kxVehicleBoxUpGoods.setStates(GoodsUpVehicleBoxType.IN_FOR_VEHICLE.getCode());
        kxVehicleBoxUpGoods.setUpPerson(LoginHelper.getUsername());
        kxVehicleBoxUpGoods.setUpTime(new Date());
        kxVehicleBoxUpGoods.setUpdateTime(new Date());
        LambdaQueryWrapper<KxVehicleBoxUpGoods> wrapper1 = new LambdaQueryWrapper<>();
        //wrapper1.eq(KxVehicleBoxUpGoods::getInVehicleNumbers, bo.getInVehicleNumbers());
        if (vehicleBoxUpGoodsMapper.update(kxVehicleBoxUpGoods, wrapper1) <= 0) {
            throw new ServiceException("商品入柜失败");
        }
        return true;
    }

    /**
     * 获取所有餐车的名称
     *
     * @param bo
     * @return 结果
     */
    @Override
    public List<KxVehicleVo> vehicleBoxAllName(List<Long> vehicleIds) {
        int state = VehicleStatusType.NOMRAL.getCode();
        return vehicleMapper.getVehicleBoxAllName(state, vehicleIds);
    }
}
